import pandas as pd
import matplotlib.pyplot as plt
import os
from matplotlib import rcParams

# 设置中文显示
rcParams['font.sans-serif'] = ['SimHei']
rcParams['axes.unicode_minus'] = False

# 创建保存目录
save_dir = '饼状图生成'
os.makedirs(save_dir, exist_ok=True)

# 读取数据
df = pd.read_excel('clear_maded_food.xlsx', sheet_name='预制表格')
df = df[['age', 'sex', 'career']].astype(str)  # 确保数据类型为字符串

# 配置字典和颜色方案
config = {'sex': '性别', 'age': '年龄', 'career': '职业构成'}
color_palette = ['#66b3ff', '#99ff99', '#ffcc99', '#ff9999', '#c2c2f0', '#ffb3e6', '#c4fcef', '#ffd700']

for col in config:
    # 统计频次
    counts = df[col].value_counts()

    # 创建画布
    plt.figure(figsize=(10, 8), dpi=100)

    # 绘制饼图
    wedges, texts, autotexts = plt.pie(
        counts,
        labels=None,  # 移除默认标签
        autopct='%1.1f%%',
        startangle=90,
        colors=color_palette[:len(counts)],
        pctdistance=0.8,
        textprops={'fontsize': 10, 'color': 'black'}
    )

    # 调整数字显示位置
    plt.setp(autotexts, size=10, weight="bold")

    # 添加图例
    plt.legend(
        wedges,
        counts.index.tolist(),
        title=config[col],
        loc='center left',
        bbox_to_anchor=(1, 0, 0.5, 1)
    )

    # 设置标题
    plt.title(f'{config[col]}分布', fontsize=14, pad=20)

    # 保存图片
    plt.savefig(
        f'{save_dir}/{col}_distribution.png',
        bbox_inches='tight',
        pad_inches=0.3
    )
    plt.close()

print("饼图生成完成！")